<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicForm @register="register" @reset="handleReset" @submit="handleSubmit" />
      <BasicTable
        ref="actionRef"
        :actionColumn="actionColumn"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="handlerAddGameAnchor">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加主播
          </n-button>
        </template>
        <!-- <template #toolbar>
          <n-button type="error" @click="batchDelete">批量删除</n-button>
        </template> -->
        <template #toolbar>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <basicModal ref="modalRef" class="basicModal" @register="modalRegister" @on-ok="okModal">
      <template #default>
        <BasicForm v-if="isEdit" class="basicForm" @register="editRegister" />
        <BasicForm v-else class="basicForm" @register="addRegister" />
      </template>
    </basicModal>

    <n-modal v-model:show="showModalTree" :show-icon="false" :title="editRoleTitle" preset="dialog">
      <div class="py-3 menu-list">
        <n-tree
          :checked-keys="checkedKeys"
          :data="treeDataSource"
          :expandedKeys="expandedKeys"
          :virtual-scroll="true"
          block-line
          checkable
          style="max-height: 600px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button ghost icon-placement="left" type="info" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button ghost icon-placement="left" type="info" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button :loading="formBtnLoading" type="primary" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { addCloumns, columns, editCloumns } from './columns';
  import { useRouter } from 'vue-router';
  import { useModal } from '@/components/Modal/index';
  import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    addGameAnchor,
    AddGameAnchorParams,
    deleteGameAnchor,
    getGameAnchorList,
    updateGameAnchor,
  } from '@/api/game/gameAnchor';
  import { getChanList } from '@/api/game/chan';

  const router = useRouter();
  const message = useMessage();
  const dialog = useDialog();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const editRoleTitle = ref('');
  const checkedKeys = ref([]);
  const checkedRowKes = ref([]);
  const userDataSource = ref([]);
  const expandedKeys = ref([]);
  const updateAdmin = ref({});
  const checkedAll = ref(false);

  const chanlOptions = ref([]);
  const menuNodeKeys = ref([]);
  const isEdit = ref(false);
  const showModalTree = ref(false);
  const updateUser = ref({});
  const treeDataSource = ref([]);

  const formParams = reactive({
    name: '',
  });

  const schemas: FormSchema[] = [
    {
      field: 'name',
      component: 'NInput',
      label: '主播名称',
      componentProps: {
        placeholder: '主播名称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  const actionColumn = reactive({
    width: 100,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record: any) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '渠道绑定',
            type: 'warning',
            onClick: handleAuth.bind(null, record),
            ifShow: () => {
              return false;
            },
          },
          {
            label: '编辑',
            type: 'info',
            icon: EditOutlined,
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
          {
            label: '删除',
            type: 'error',
            icon: DeleteOutlined,
            onClick: handleDelete.bind(null, record),
            ifShow: () => {
              return false;
            },
          },
        ],
      });
    },
  });

  const [modalRegister, { openModal, closeModal, setSubLoading, setProps }] = useModal({
    title: '编辑',
    width: 600,
  });
  const [addRegister, { submit: addSubmit, setFieldsValue: addSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: addCloumns,
  });

  const [editRegister, { submit: editSubmit, setFieldsValue: editSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: editCloumns,
  });

  //提交数据
  async function okModal() {
    if (unref(isEdit)) {
      await submitEdit();
    } else {
      await submitAdd();
    }
  }

  async function submitEdit() {
    let formRes = {};
    try {
      formRes = await editSubmit();
      let tmp = unref(updateAdmin);
      let params: any = Object.assign(tmp, formRes);
      const gameAnchorParam = params as any as AddGameAnchorParams;
      await updateGameAnchor(gameAnchorParam);
      closeModal();
      reloadTable();
      message.success('编辑成功');
    } catch (e) {
      if (!formRes) {
        message.error('验证失败，请填写完整信息');
      }
    } finally {
      setSubLoading(false);
    }
  }

  async function confirmForm(e: any) {
    e.preventDefault();
    try {
      formBtnLoading.value = true;
      let chanId = [];
      for (let key of unref(checkedKeys)) {
        chanId.push(key);
      }
      let params = {
        ...unref(updateUser),
        chanId: chanId.length > 0 ? chanId.join(',') : '',
      };
      await updateGameAnchor(params);
      message.success('绑定成功');
      setTimeout(() => {
        showModalTree.value = false;
        reloadTable();
      });
    } finally {
      formBtnLoading.value = false;
    }
  }

  async function submitAdd() {
    let formRes = {};
    try {
      formRes = await addSubmit();
    } catch (e) {
      message.error('验证失败，请填写完整信息');
      setSubLoading(false);
    }
    try {
      let params: any = Object.assign({}, formRes);
      params.chanId = unref(params.chanId) ? unref(params.chanId).join(',') : '';
      params = Object.assign(
        {},
        {
          id: 0,
          createTime: '',
          updateTime: '',
          userId: '',
          chanId: '',
          name: '',
          iosCommand: '',
        },
        params
      );
      const adminParam = params as any as AddGameAnchorParams;
      await addGameAnchor(adminParam);
    } finally {
      setSubLoading(false);
    }
    closeModal();
    reloadTable();
    message.success('添加成功');
  }

  async function handleAuth(record: any) {
    editRoleTitle.value = `绑定 ${record.name} 的渠道`;

    let firstPsids = record.chanId.split(',');

    let menuKeys = unref(menuNodeKeys);

    checkedKeys.value = [];

    function handKeys(key: string) {
      if (!checkedKeys.value.includes(key)) {
        if (key && key != '') {
          checkedKeys.value.push(key);
        }
      }
    }

    for (let psIds of firstPsids) {
      handKeys(psIds);
    }

    updateUser.value = record;
    showModalTree.value = true;
  }

  function onCheckedRow(rowKeys: any[]) {
    checkedRowKes.value = rowKeys;
  }

  function checkedTree(keys) {
    checkedKeys.value = [...keys];
  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function checkedAllHandle() {
    if (!checkedAll.value) {
      checkedKeys.value = menuNodeKeys.value;
      checkedAll.value = true;
    } else {
      checkedKeys.value = [];
      checkedAll.value = false;
    }
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = treeDataSource.value.map((item: any) => item.key) as [];
    }
  }

  function reloadTable() {
    // loadUserDataSource();
    actionRef.value.reload();
  }

  async function handlerAddGameAnchor() {
    isEdit.value = false;
    setProps({
      title: '添加主播',
    });
    await openModal();
  }

  async function handleEdit(record: any) {
    isEdit.value = true;
    updateAdmin.value = unref(record);
    setProps({
      title: '编辑',
    });
    await openModal();
    const fileds: any = Object.assign({}, unref(record));
    fileds.status = record.status == 'able';
    if (fileds.chanId && fileds.chanId != '') {
      fileds.chanId = fileds.chanId.split(',');
    }

    editSetFieldsValue(fileds);
    // router.push({ name: 'basic-info', params: { id: record.id } });
  }

  function handleDelete(record: Recordable) {
    dialog.info({
      title: '提示',
      content: `您想删除${record.name}吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteGameAnchor(record);
        message.success('删除成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  //批量删除
  function batchDelete() {
    const userids = unref(checkedRowKes);
    if (userids.length === 0) {
      message.warning('至少选择一条数据');
      return;
    }
    dialog.info({
      title: '提示',
      content: `您想删除选中主播吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await await deleteGameAnchor(record);
        ({ idArrs: userids });
        message.success('删除成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  // 加载用户数据
  const loadUserDataSource = async (res) => {
    if (!formParams.name) {
      formParams.name = '';
    }
    const param = { ...formParams, ...res }; //分页的关键
    console.log(param);
    const dataSource = await getGameAnchorList(param);
    userDataSource.value = dataSource.list;
  };

  onMounted(async () => {
    //加载用户数据
    // await loadUserDataSource();
    // 加载权限树
    // await loadTreeValues();
  });

  const loadDataTable = async (res) => {
    if (!formParams.name) {
      formParams.name = '';
    }
    const param = { ...formParams, ...res }; //分页的关键
    console.log(param);
    return await getGameAnchorList(param);
  };

  async function loadTreeValues() {
    let res = await getChanList();

    for (let item: any of res.list) {
      item.label = item.chanName;
      item.key = item.chanId;
      unref(menuNodeKeys).push(item.chanId);
    }

    treeDataSource.value = res.list as any[];
  }

  function handleSubmit(values: Recordable) {
    console.log('submit', values);
    let tempParams = unref(formParams);
    tempParams = Object.assign(tempParams, values);
    reloadTable();
  }
</script>

<style lang="less" scoped></style>
